import getApi from "../../result/api";
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
function Login() {
   const [username, setUsername] = useState("");
   const [password, setPassword] = useState("");
   const [error, setError] = useState("");
   const navigate = useNavigate();
   const handleSubmit = async () => {
      try {
         const { code, result } = await getApi({
            url: "/user/login",
            method: "post",
            data: { username, password },
         });
         if (code == 200) {
            // 存储 token
            localStorage.setItem("token", true);
            sessionStorage.setItem("userId", JSON.stringify(result._id));
            sessionStorage.setItem("result", JSON.stringify(result));
            sessionStorage.setItem("userName", username);
            // 跳转到首页
            navigate("/message");
         } else {
            setError("登陆失败，请检查您的用户名和密码");
         }
      } catch (error) {
         console.log(error);
         setError("登陆失败，请检查您的用户名和密码");
      }
   };
   return (
      <div className='login'>
         <header>
            <h3 style={{ fontSize: "0.3rem", marginBottom: "0" }}>用户登陆</h3>
         </header>
         <main style={{ fontSize: "0.3rem" }}>
            {/* 用户名输入框 */}
            <input style={{ fontSize: "0.3rem" }} type='text' placeholder='Username' value={username} onChange={(e) => setUsername(e.target.value)} />
            {/* 密码输入框 */}
            <input style={{ fontSize: "0.3rem" }} type='password' placeholder='Password' value={password} onChange={(e) => setPassword(e.target.value)} />
            {/* 登陆按钮 */}
            <button style={{ fontSize: "0.3rem" }} onClick={handleSubmit}>
               Login
            </button>
         </main>
         <footer></footer>
      </div>
   );
}

export default Login;
